import { ethers } from "ethers";
import { getNetwork } from "../const/Networks";

/**
 * 钱包工具类 - 提供与MetaMask和其他区块链钱包的交互功能
 */
export default {
  /**
   * 检查是否安装了MetaMask
   * @returns {boolean} 是否安装了MetaMask
   */
  isMetaMaskInstalled() {
    return window.ethereum && window.ethereum.isMetaMask;
  },

  /**
   * 连接到MetaMask钱包
   * @returns {Promise<string>} 钱包地址
   */
  async connectMetaMask() {
    if (!this.isMetaMaskInstalled()) {
      throw new Error("请先安装MetaMask钱包");
    }

    try {
      // 请求用户授权连接钱包
      const accounts = await window.ethereum.request({
        method: "eth_requestAccounts",
      });
      return accounts[0];
    } catch (error) {
      console.error("连接MetaMask失败:", error);
      throw new Error(error.message || "连接钱包失败");
    }
  },

  /**
   * 获取当前连接的钱包地址
   * @returns {Promise<string|null>} 钱包地址或null
   */
  async getCurrentAddress() {
    if (!this.isMetaMaskInstalled()) {
      return null;
    }

    try {
      const accounts = await window.ethereum.request({
        method: "eth_accounts",
      });
      return accounts.length > 0 ? accounts[0] : null;
    } catch (error) {
      console.error("获取钱包地址失败:", error);
      return null;
    }
  },

  /**
   * 验证以太坊地址是否有效
   * @param {string} address 以太坊地址
   * @returns {boolean} 是否有效
   */
  isValidAddress(address) {
    return ethers.utils.isAddress(address);
  },

  /**
   * 获取钱包余额
   * @param {string} address 钱包地址
   * @param {string} networkId 网络ID
   * @returns {Promise<string>} 余额（原生代币）
   */
  async getBalance(address, networkId = "ethereum") {
    try {
      const network = getNetwork(networkId);
      const provider = new ethers.providers.JsonRpcProvider(network.rpcUrl);
      const balance = await provider.getBalance(address);
      return {
        balance: ethers.utils.formatEther(balance),
        symbol: network.symbol,
      };
    } catch (error) {
      console.error(`获取${networkId}网络余额失败:`, error);
      throw new Error(`获取${networkId}网络钱包余额失败`);
    }
  },

  /**
   * 获取当前网络ID
   * @returns {Promise<string>} 网络ID
   */
  async getCurrentNetworkId() {
    if (!this.isMetaMaskInstalled()) {
      return "ethereum"; // 默认返回以太坊
    }

    try {
      const chainId = await window.ethereum.request({ method: "eth_chainId" });
      // 根据chainId映射到我们定义的networkId
      switch (chainId) {
        case "0x1":
        case "0xaa36a7": // Sepolia
          return "ethereum";
        case "0x38":
        case "0x61": // BSC测试网
          return "bsc";
        case "0x89":
        case "0x13881": // Mumbai
          return "polygon";
        case "0xa4b1":
        case "0x66eed": // Arbitrum Sepolia
          return "arbitrum";
        default:
          return "ethereum";
      }
    } catch (error) {
      console.error("获取当前网络ID失败:", error);
      return "ethereum"; // 默认返回以太坊
    }
  },

  /**
   * 监听钱包账户变化
   * @param {Function} callback 回调函数
   */
  onAccountsChanged(callback) {
    if (this.isMetaMaskInstalled()) {
      window.ethereum.on("accountsChanged", callback);
    }
  },

  /**
   * 监听网络变化
   * @param {Function} callback 回调函数
   */
  onChainChanged(callback) {
    if (this.isMetaMaskInstalled()) {
      window.ethereum.on("chainChanged", callback);
    }
  },
};
